import {OrgItem} from '@/pages/Enterprise/Org/data';
import React, {useRef, useState} from 'react';
import ProTable, {ActionType, EditableProTable, ProColumns} from '@ant-design/pro-table';
import {loadPostSelect} from '@/pages/Enterprise/Post/service';
import {EmployeeBody, EmployeeListItem, OrgPost} from '@/pages/Employee/List/data';
import {
  addEmployee,
  employeeList,
  loadEmployee,
  updateEmployee,
} from '@/pages/Employee/List/service';
import {Button, Form, FormInstance, Tag} from 'antd';
import {ModalForm, ProForm, ProFormRadio, ProFormSelect, ProFormText} from '@ant-design/pro-form';

type EmployeeListProps = {
  orgId?: number;
  orgName: string;
  orgList: OrgItem[];
  actionRef?: React.Ref<ActionType | undefined>;
};

const EmployeeList: React.FC<EmployeeListProps> = (props) => {
  const {orgId, orgName, orgList, actionRef: propsActionRef} = props;

  const requestOrg = async () => {
    return orgList;
  };
  const requestPost = async () => {
    return loadPostSelect().then(({data}) => {
      return data;
    });
  };

  const saveSubmit = async (values: EmployeeBody) => {
    await editForm.validateFields(); // 调用表单验证
    try {
      if (values?.employeeId > 0) {
        await updateEmployee(values);
      } else {
        await addEmployee(values);
      }
      actionRef.current?.reload();
    } catch (e) {
      return false;
    }
    return true;
  };
  const [editForm] = Form.useForm()
  const orgPostColumns: ProColumns<OrgPost>[] = [
    {
      title: '部门',
      key: 'orgId',
      dataIndex: 'orgId',
      valueType: 'treeSelect',
      request: requestOrg,
      fieldProps: {
        dropdownMatchSelectWidth: false,
        placeholder: '请选择部门',
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
        treeLine: true,
        treeDefaultExpandAll: true,
        fieldNames: {label: 'label', value: 'id', children: 'children'},
      },
    },
    {
      title: '岗位',
      key: 'postId',
      dataIndex: 'postId',
      valueType: 'select',
      request: requestPost,
      fieldProps: {
        dropdownMatchSelectWidth: false,
        placeholder: '请选择岗位',
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
        // fieldNames: {label: 'postName', value: 'postId'},
      },
    },
    {
      title: '管理类型',
      key: 'managerType',
      dataIndex: 'managerType',
      valueType: 'select',
      request: async () => {
        return [
          {value: 10, label: '员工'},
          {value: 11, label: '主管'},
        ];
      },
    },
    {
      title: '是否含下级',
      key: 'hasLeaf',
      dataIndex: 'hasLeaf',
      valueType: 'select',
      request: async () => {
        return [
          {value: 0, label: '不包含'},
          {value: 1, label: '包含'},
        ];
      },
    },
    {
      width: 50,
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => {
        return [];
      },
    },
  ];
  const columns: ProColumns<EmployeeListItem>[] = [
    {
      dataIndex: 'index',
      width: 48,
      align: 'center',
      valueType: 'index',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
              (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '员工姓名',
      key: 'name',
      dataIndex: 'name',
    },
    {
      title: '手机号',
      key: 'mobile',
      dataIndex: 'mobile',
    },
    {
      title: '身份证号',
      key: 'idCard',
      dataIndex: 'idCard',
    },
    {
      title: '岗位',
      key: 'postId',
      dataIndex: 'postName',
      valueType: 'select',
      // @ts-ignore
      request: async () => {
        return loadPostSelect().then(({data}) => {
          return data;
        });
      },

      render: (_, record) => (
        <>
          {record.postName.map((name, index) => (
            <Tag key={name + index + record.employeeId}>{name}</Tag>
          ))}
        </>
      ),
    },
    {
      title: '注册时间',
      key: 'createTime',
      search: false,
      dataIndex: 'createTime',
      valueType: 'dateTime',
    },
    {
      title: '操作',
      key: 'option',
      width: 80,
      valueType: 'option',
      render: (_, record) => [
        <a
          key={record.employeeId}
          onClick={() => {
            formRef.current?.resetFields();
            record.flag = Date.now();
            setCurrentRow(record);
            handleModalVisible(true);
          }}
        >
          编辑
        </a>,
      ],
    },
  ];
  const actionRef = useRef<ActionType>();
  if (propsActionRef) {
    // @ts-ignore
    propsActionRef.current = actionRef.current;
  }
  const formRef = useRef<FormInstance>();
  const [currentRow, setCurrentRow] = useState<EmployeeListItem>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>();
  let defaultKey = Date.now();
  return (
    <>
      <ProTable<EmployeeListItem>
        columns={columns}
        request={async (params, a, c) => {
          return employeeList({...params, orgId: orgId});
        }}
        actionRef={actionRef}
        pagination={{
          pageSize: 10,
          showSizeChanger: false,
        }}
        headerTitle={orgName + ' - 员工列表'}
        params={{orgId}}
        rowKey="employeeId"
        options={false}
        toolbar={{
          actions: [
            <Button
              key="import-employee"
              type="primary"
              disabled
              onClick={() => {
                // actionRef.current?.reset();
              }}
            >
              导入
            </Button>,
            <Button
              key="add-employee"
              type="primary"
              onClick={() => {
                formRef.current?.resetFields();
                handleModalVisible(true);
              }}
            >
              添加员工
            </Button>,
          ],
        }}
      />
      <ModalForm<EmployeeBody>
        title={currentRow?.employeeId || 0 > 0 ? '编辑员工' : '添加员工'}
        // width="600px"
        formRef={formRef}
        visible={createModalVisible}
        onVisibleChange={(visible) => {
          if (!visible) {
            setCurrentRow(undefined);
          }
          handleModalVisible(visible);
        }}
        onFinish={saveSubmit}
        request={(params) => {
          if (params.employeeId > 0) {
            return loadEmployee(params).then(({data}) => {
              setEditableRowKeys(() => data?.orgPostList.map((item) => item.id));
              return data;
            });
          } else {
            setEditableRowKeys([defaultKey]);
            return new Promise<EmployeeBody>((resolve, reject) => {
              resolve({
                enterpriseEmployeeId: 0,
                employeeId: 0,
                password: '',
                name: '',
                mobile: '',
                idCard: '',
                status: 0,
                workType: 0,
                practitionersType: 0,
                remark: '',
                orgPostList: [
                  {
                    id: defaultKey,
                    orgId: orgId,
                    managerType: 10,
                    hasLeaf: 0,
                  },
                ],
              });
            });
          }
        }}
        params={{...currentRow, orgId}}
      >
        <ProFormText hidden name="employeeId"/>
        <ProFormText hidden name="enterpriseEmployeeId"/>
        <ProFormText
          rules={[
            {
              required: true,
              message: '手机号',
            },
          ]}
          label={'手机号'}
          placeholder={'请输入手机号码'}
          name="mobile"
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '员工姓名',
            },
          ]}
          label={'员工姓名'}
          placeholder={'请输入员工姓名'}
          name="name"
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '身份证号',
            },
          ]}
          label={'身份证号'}
          placeholder={'请输入身份证号'}
          name="idCard"
        />

        <ProFormText.Password
          tooltip={'默认密码为身份证号码后6位'}
          label={'密码'}
          placeholder={'请输入账号密码'}
          name="password"
        />

        <ProForm.Item label="部门和岗位" name="orgPostList" trigger="onValuesChange">
          <EditableProTable<OrgPost>
            rowKey="id"
            toolBarRender={false}
            columns={orgPostColumns}
            onChange={(value) => {
              console.log(value);
            }}
            controlled={true}
            maxLength={5}
            recordCreatorProps={{
              creatorButtonText: '新增部门',
              newRecordType: 'dataSource',
              record: () => ({
                id: Date.now(),
              }),
            }}
            editable={{
              form: editForm,
              type: 'multiple',
              editableKeys,
              onChange: setEditableRowKeys,
              actionRender: (row, _, dom) => {
                return [dom.delete];
              },
            }}
          />
        </ProForm.Item>
        <ProFormRadio.Group
          rules={[
            {
              required: true,
              message: '在职类型',
            },
          ]}
          name="workType"
          label="在职类型"
          options={[
            {
              label: '全职',
              value: 1,
            },
            {
              label: '兼职',
              value: 2,
            },
          ]}
        />
        <ProFormSelect
          name="practitionersType"
          label="从业类型"
          request={async () => [
            {label: '普通从业人员', value: 0},
            {label: '特种从业人员', value: 1},
            {label: '安全管理员', value: 3},
            {label: '企业主要负责人', value: 4},
            {label: '安全管理员+普通从业人员', value: 5},
            {label: '其它', value: 2},
          ]}
          rules={[{required: true}]}
        />
      </ModalForm>
    </>
  );
};
export default EmployeeList;
